package JZ;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Classname JZ32III
 * @Description // https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/submissions/ 树 一次ac
 * @Date 2021/4/21 15:12
 * @Created by yin
 */
public class JZ32III {
    public List<List<Integer>> levelOrder(TreeNode root) {

        LinkedList<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) return list;
        queue.add(root);
        boolean left = false;
        while (!queue.isEmpty()) {
            left = !left;
            int size = queue.size();
            LinkedList<Integer> temp = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.remove();
                if (left) {
                    temp.add(node.val);
                } else {
                    temp.addFirst(node.val);
                }
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            list.add(temp);
        }
        return list;
    }
}
